<template>
  <div class="app-container">

    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="12">
            项目：
            <el-select
              v-model="project_id"
              v-loading="projectsLoading"
              placeholder="项目"
              filterable
              clearable
            >
              <el-option
                v-for="item in projects"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            网站:
            <single_wpaccount_select :wpaccount_id="wpaccount_id" size="small" @change="changeWPAccount" />
            策略：
            <el-select
              v-model="strategy_id"
              v-loading="strategysLoading"
              placeholder="分类"
              filterable
              clearable
            >
              <el-option
                v-for="strategy in strategies"
                :key="strategy.id"
                :label="strategy.name"
                :value="strategy.id"
              />
            </el-select>
            <el-button
              type="warning"
              size="mini"
              title="策略管理"
              icon="el-icon-setting"
              @click="webVisible = true"
            />

          </el-col>
          <el-col :span="12">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-input v-model="TagInput" placeholder="请输入内容">
                  <template slot="prepend">TAG</template>
                </el-input>
              </el-col>
              <el-col :span="12">
                <el-input
                  v-model="kwInput"
                  placeholder="输入关键词进行筛选"
                  class="input-with-select"
                  clearable
                  @keyup.native.enter="handleSearch"
                >
                  <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                </el-input>
              </el-col>
            </el-row>

          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-button
            type="warning"
            size="mini"
            title="添加素材"
            icon="el-icon-setting"
            @click="titleTopicDialogVisible = true"
          >添加素材
          </el-button>
        </el-aside>
        <el-main>
          <el-table
            v-loading.body="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            style="width: 100%"
            @cell-mouse-enter="(m) => m.active=true"
            @cell-mouse-leave="(m) => m.active=false"
            @sort-change="handleSort"
          >

            <el-table-column align="left" label="标题" prop="title" sortable="custom">
              <template slot-scope="scope">
                <span class="" :title="scope.row.title">{{ scope.row.title }}</span>
                {{ '[' + scope.row.tag + ']' }}
                <div v-if="scope.row.active" class="mt-row-btns">
                  <a class="mt-btn danger" title="删除话题" @click="handleClickDelete(scope.row)">
                    <i class="el-icon-delete mt-icon" /></a>
                  <a class="mt-btn" title="查看" @click="handleClickView(scope.row)">
                    <i class="el-icon-view mt-icon" /></a>
                  <a class="mt-btn" title="管理" @click="handleClickView(scope.row)">
                    <i class="el-icon-more mt-icon" /></a>
                  <a class="mt-btn default" title="添加素材" @click="handleAddMaterial(scope.row.id)">
                    <i class="el-icon-share mt-icon" /></a>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="完成进度" prop="progress" width="160" sortable="custom">
              <template slot-scope="scope">
                <el-progress v-if="scope.row.progress < 100" :percentage="scope.row.progress" status="exception" />
                <el-progress v-else :percentage="100" status="success" />
              </template>
            </el-table-column>

            <el-table-column align="center" label="作者" prop="owner__name" width="210" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.owner__username }}|{{ scope.row.project_name }}
                <br>
                {{ scope.row.website__domain }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="最后更新" prop="update_at" sortable="update_at" width="180px" />

          </el-table>
          <el-pagination
            v-if="data.length"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10,20,50,100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />

          <topicstrategy :web-visible="webVisible" @closeWebDialog="webVisible=false" />
        </el-main>

      </el-container>
    </el-container>
    <el-dialog
      v-loading.fullscreen.lock="deleteDialogLoading"
      :title="deleteDialogTitle"
      :visible.sync="deleteDialogVisible"
      style="margin-top: 148px !important;"
    >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleDeleteConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="titleTopicDialog"
      :visible.sync="titleTopicDialogVisible"
      style="margin-top: 10px !important;"
    >
      <el-form ref="dataForm" :model="topicTemp" label-position="left" label-width="40px">
        <el-form-item label="title">
          <el-input v-model="topicTemp.title" />
        </el-form-item>
        <el-form-item label="内容">
          <tinymce ref="mt" v-model="topicTemp.description" :height="300" />
        </el-form-item>
        <el-form-item label="tag">
          <el-input v-model="topicTemp.tag" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCleanTopicForm">清空内容</el-button>
        <el-button @click="titleTopicDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleAddTopicsMaterial">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="titleTopicViewDialog"
      :visible.sync="TopicViewDialogVisible"
      style="margin-top: 10px !important;"
    >
      <h3>{{ topicViewData.title }}</h3>
      <hr>
      <div style="display: block; font-size: 14px" v-html="topicViewData.description" />
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="HanldeEditTopic">编 辑</el-button>
        <el-button @click="TopicViewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as Getstrategies } from '@/api/cms/topicstrategy'
import { Put, Delete, Post as AddTopicsMaterial, Get as GetTopicsMaterial } from '@/api/cms/topicmaterial'
import { Get as GetUsers } from '@/api/users'
import clip from '@/utils/clipboard' // use clipboard directly
import topicstrategy from '@/views/cms/elements/topicstrategy'
import Tinymce from '@/components/Tinymce'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

import Cookies from 'js-cookie'
import Single_wpaccount_select from './elements/single_wpaccount_select'

const ProjectKey = 'cms_project_id__search'
const StrotegyKey = 'cms_strategy_id__search'
const OwnerKey = 'cms_language_id__owner'

export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  return Cookies.set(key, value)
}

export default {
  components: { Single_wpaccount_select, topicstrategy, Tinymce },
  data() {
    return {
      wpaccount_id: '',
      TopicViewDialogVisible: false,
      titleTopicViewDialog: '查看内容',
      topicViewData: {
        title: '',
        description: '',
        tag: '',
        strategy_id: '',
        keyword: '',
        progress: 0
      },
      topicEditId: '',
      titleTopicDialog: '添加新话题',
      titleTopicDialogVisible: false,
      topicTemp: {
        title: '',
        description: '',
        tag: '',
        strategy_id: '',
        keyword: '',
        id: '',
        progress: 0
      },
      listLoading: false,
      webVisible: false,
      projects: [],
      project_id: null,
      projectsLoading: false,

      strategies: [],
      strategy_id: null,
      strategysLoading: false,

      languages: [],
      language_id: null,
      languagesLoading: false,

      users: [],
      owner_id: null,
      ownersLoading: false,

      webs: [],
      web_id: null,
      websLoading: false,

      title: '',
      content: '',
      saveDisabled: false,
      init_text: '',

      kwInput: '',
      TagInput: '',
      data: [],
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      m_active: false,

      deleteDialogVisible: false,
      deleteDialogTitle: '',
      deleteId: null,
      deleteDialogLoading: false
    }
  },
  created() {
    this.project_id = getToken(ProjectKey)
    this.strategy_id = getToken(StrotegyKey)
    this.owner_id = getToken(OwnerKey)
    console.log(111, this.project_id)

    this.handleFetchProjects()
    this.handleFetchstrategies()
    this.handleFetchGetUsers()
    this.getList()
  },
  methods: {
    changeWPAccount(v) {
      this.wpaccount_id = v
    },
    handleFetchProjects() {
      this.projectsLoading = true
      GetProjects()
        .then(response => {
          this.projectsLoading = false
          this.projects = response.data.data
          if (this.projects.length) {
            this.project_id = getToken(ProjectKey) || null
          }
        })
        .catch(e => {
          this.projectsLoading = false
        })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleFetchstrategies() {
      this.strategysLoading = true
      Getstrategies()
        .then(response => {
          this.strategysLoading = false
          this.strategies = response.data.data
          if (this.strategies.length) {
            this.strategy_id = getToken(StrotegyKey) || null
          }
        })
        .catch(e => {
          this.strategysLoading = false
        })
    },
    handleFetchGetUsers() {
      this.ownersLoading = true
      GetUsers()
        .then(response => {
          this.ownersLoading = false
          this.users = response.data.data
          if (this.users.length) {
            this.owner_id = getToken(OwnerKey) || null
          }
        })
        .catch(e => {
          this.ownersLoading = false
        })
    },
    getList(loading) {
      if (loading === undefined) {
        loading = true
      }
      this.listLoading = loading
      GetTopicsMaterial(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc,
        owner_id: this.owner_id,
        project_id: this.project_id,
        strategy_id: this.strategy_id
      }))
        .then(response => {
          this.scrollTop()
          setToken(ProjectKey, this.project_id)
          setToken(StrotegyKey, this.strategy_id)
          setToken(OwnerKey, this.owner_id)
          this.data = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          this.listLoading = false
          this.total = response.data.total
        }).catch(e => {
          this.listLoading = false
          setToken(ProjectKey, this.project_id)
          setToken(StrotegyKey, this.strategy_id)
          setToken(OwnerKey, this.owner_id)
        })
    },
    HanldeEditTopic() {
      this.topicTemp.title = this.topicViewData.title
      this.topicTemp.keyword = this.topicViewData.keyword
      this.topicTemp.tag = this.topicViewData.tag
      this.topicTemp.description = this.topicViewData.description
      this.topicEditId = this.topicViewData.id
      this.$nextTick(() => {
        this.$refs.mt.setContent(this.topicTemp.description)
      })
      this.titleTopicDialog = '编辑话题-' + this.topicTemp.id
      this.topicTemp.strategy_id = this.topicViewData.strategy_id
      this.TopicViewDialogVisible = false
      this.titleTopicDialogVisible = true
    },
    handleAddTopicsMaterial() {
      this.topicTemp.progress = 0
      this.topicTemp.strategy_id = this.strategy_id
      if (this.topicEditId !== '') {
        Put(this.topicEditId, JSON.stringify(this.topicTemp)).then(response => {
          this.notify('修改成功')
          this.getList()
          this.titleTopicDialogVisible = false
          this.handleCleanTopicForm()
        }).catch(e => {
          this.notify('修改失败')
          this.titleTopicDialogVisible = false
          this.handleCleanTopicForm()
        })
      } else {
        AddTopicsMaterial(JSON.stringify(this.topicTemp)).then(response => {
          this.notify('保存成功')
          this.getList()
          this.titleTopicDialogVisible = false
        }).catch(e => {
          this.notify('保存失败')
          this.titleTopicDialogVisible = false
        })
      }
    },
    handleCleanTopicForm() {
      this.topicTemp.title = ''
      this.topicTemp.description = ''
      this.topicTemp.keyword = ''
      this.topicTemp.tag = ''
      this.topicEditId = ''
      this.$nextTick(() => {
        this.$refs.mt.setContent('')
      })
    },
    handleAddMaterial(id) {
      console.log('id')
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleClickEdit(id) {
      const link = this.$router.resolve({ name: 'editPostPut', params: { post_id: id }})
      window.open(link.href, '_blank')
    },
    handleClickView(row) {
      // this.$router.push({ name: 'viewPost', params: { post_id: id }})
      this.topicViewData = row
      this.TopicViewDialogVisible = true
    },
    handleClickDelete(row) {
      this.deleteDialogVisible = true
      this.deleteDialogTitle = `确认要删除话题 ${row.title}?`
      this.deleteId = row.id
    },
    handleDeleteConfirm() {
      this.deleteDialogLoading = true
      Delete(this.deleteId)
        .then(res => {
          this.deleteDialogLoading = false
          this.deleteDialogVisible = false
          this.getList()
        }).catch(e => {
          this.deleteDialogLoading = false
        })
    },
    handleClickShare(v, event) {
      const link = this.$router.resolve({
        name: 'viewPost',
        params: {
          post_id: v
        }
      })
      clip(window.location.origin + '/' + link.href, event)
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    handleChangePostFinishStatus(row) {
      Put(row.id, JSON.stringify({
        is_finished: row.is_finished,
        put_finished: 1
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '修改状态成功',
            type: 'success',
            duration: 1000
          })
          this.getList(false)
        })
        .catch(e => {
        })
    }
  }
}
</script>

<style scoped>

  .el-header, .el-footer {
    background-color: #fff;
    color: #333;
    text-align: left;
    line-height: 60px;
  }

  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    line-height: 200px;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  /*.top {*/
  /*padding-left: 20px;*/
  /*padding-right: 20px;*/
  /*margin-bottom: 5px;*/
  /*margin-top: 28px;*/
  /*}*/

  /*.head {*/
  /*width: calc(20% - 70px);*/
  /*}*/

  /*.web {*/
  /*margin-top: 10px;*/
  /*margin-bottom: 10px;*/
  /*display: inline-block;*/
  /*width: 100%;*/
  /*}*/

  .web >>> .el-input {
    min-width: 1200px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-detail:hover, .svg-icon:hover {
    cursor: pointer;
  }

  .mt-detail {
    color: #1976d2;
  }

  .mt-dialog >>> .el-dialog {
    margin: 88px auto !important;
  }

  .clearfix ::after {
    content: "";
    clear: both
  }

  .mt-table {
    color: black;
    padding: 20px;
  }

  .mt-pagination {
    float: right;
    margin-top: 10px;
  }

  .mt-top {
    margin: 15px 0;
  }

  .mt-row-btn {
    float: right;
    vertical-align: middle;
    color: white;
  }

  .mt-btn {
    background-color: rgba(0, 0, 0, 0);
    background-image: none;
    border-radius: 1000px;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-collapse: collapse;
    border-image-outset: 0px;
    border-image-repeat: stretch;
    border-image-slice: 100%;
    border-image-source: none;
    border-image-width: 1;
    border-left-style: solid;
    border-left-width: 1px;
    border-right-style: solid;
    border-right-width: 1px;
    border-top-style: solid;
    border-top-width: 1px;
    box-sizing: border-box;
    color: #46be8a;
    cursor: pointer;
    display: block;
    float: right;
    font-family: "Helvetica Neue", Helvetica, Tahoma, Arial, "Microsoft Yahei", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif;
    font-size: 14px;
    font-weight: 400;
    height: 26px;
    hyphens: manual;
    line-height: 14px;
    margin-bottom: 0px;
    margin-right: 10px;
    padding: 5px;
    text-align: center;
    text-decoration-color: rgb(82, 96, 105);
    text-decoration-line: none;
    text-decoration-style: solid;
    text-rendering: optimizeLegibility;
    text-size-adjust: 100%;
    touch-action: manipulation;
    transition-delay: 0s, 0s, 0s, 0s;
    transition-duration: 0.2s, 0.2s, 0.2s, 0.2s;
    transition-property: border, color, width, background-color;
    transition-timing-function: linear, linear, linear, linear;
    user-select: none;
    vertical-align: middle;
    visibility: visible;
    white-space: nowrap;
    background: white;
  }

  .mt-btn:hover + >>> .mt-icon {
    color: #fff;
  }

  .mt-btn:hover {
    background: #46be8a;
  }

  .danger:hover {
    background-color: #F56C6C;
  }

  .danger {
    color: #F56C6C;
  }

  .default:hover {
    background-color: #62a8ea;
  }

  .default {
    color: #62a8ea;
  }

  .edit:hover {
    background-color: #909399;
  }

  .edit {
    color: #909399;
  }

  .mt-row-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: calc(100% - 220px);
    display: inline-block;
    vertical-align: middle;
  }

  .mt-row-btns {
    float: right;
    margin-right: 10px;
    z-index: 10000;
  }

</style>
